package com.ebook.service.implement;

import com.ebook.database.dao.UserDao;
import com.ebook.entity.User;
import com.ebook.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public boolean existUser(String userName) {
        return userDao.selectUserByUserName(userName)!=null;
    }

    @Override
    public User selectUserByUserNameAndPassword(String userName, String password) {
        return userDao.selectUserByUserNameAndPassword(userName, password);
    }


    @Override
    public List<User> selectAll() {
        return userDao.selectAll();
    }

    @Override
    public void deleteUser(User user) {
        userDao.deleteUser(user);
    }

    @Override
    public void addUser(User user) {
        boolean existUser = existUser(user.getUserName());
        if(!existUser){
            user.setIsVip(false);
            userDao.addUser(user);
        }
    }

    @Override
    public void updateUser(User user) {
        boolean existUser = existUser(user.getUserName())&&
                !Objects.equals(user.getUserId(),
                        userDao.selectUserByUserName(user.getUserName()).getUserId());
        //用户更改用户名时,不能和已有用户名重名
        /*
            A,B
            A 表示存在该用户名用户
            B 表示 用户名相同的Id 与该用户Id不相同
            A-B 0
            -A -B
            -A B
            AB 1 不能改
        */
        /*
         * 如果不改userName,那么需要保证 用户能够被改,用户名相同(Id也相同).
         * 如果改userName,需要保证用户能修改, 那么需要保证数据库中没有(Id不同)相同的用户名的用户,
         * **/
        if(!existUser){
            userDao.updateUser(user);
        }

    }

    @Override
    public void deleteUser(String userName, String password) {
        User user = userDao.selectUserByUserNameAndPassword(userName, password);
        this.deleteUser(user);
    }

    @Override
    public void becomeVip(String userName) {
        userDao.becomeVip(userName);
    }

    @Override
    public User selectUserByUserId(Integer userId) {
        return userDao.selectUserByUserId(userId);
    }

}
